package cn.lblbc.cootext

import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

class SearchHistoryManager(context: Context) {
    private val prefs: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
    private val gson = Gson()
    
    companion object {
        private const val PREFS_NAME = "search_history_prefs"
        private const val KEY_SEARCH_HISTORY = "search_history"
        private const val MAX_HISTORY_SIZE = 20
    }
    
    fun getSearchHistory(): List<String> {
        val json = prefs.getString(KEY_SEARCH_HISTORY, null) ?: return emptyList()
        val type = object : TypeToken<List<String>>() {}.type
        return try {
            gson.fromJson(json, type)
        } catch (e: Exception) {
            emptyList()
        }
    }
    
    fun addSearchQuery(query: String) {
        if (query.isBlank()) return
        
        val history = getSearchHistory().toMutableList()
        
        // 如果已存在相同的查询，先移除它
        history.remove(query)
        
        // 添加到列表开头
        history.add(0, query)
        
        // 如果超过最大数量，移除最旧的
        if (history.size > MAX_HISTORY_SIZE) {
            history.removeAt(history.size - 1)
        }
        
        // 保存更新后的历史记录
        saveSearchHistory(history)
    }
    
    fun removeSearchQuery(query: String) {
        val history = getSearchHistory().toMutableList()
        history.remove(query)
        saveSearchHistory(history)
    }
    
    fun clearSearchHistory() {
        saveSearchHistory(emptyList())
    }
    
    private fun saveSearchHistory(history: List<String>) {
        val json = gson.toJson(history)
        prefs.edit().putString(KEY_SEARCH_HISTORY, json).apply()
    }
}